package com.wecloud.core.server;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.wecloud.core.constant.ErrorMsg;
import com.wecloud.core.constant.WeContext;
import com.wecloud.core.exception.WeException;
import com.wecloud.core.user.WeUser;
import com.wecloud.core.utils.JsonUtils;
import com.wecloud.redis.service.RedisService;

public class InitContext {
	@Autowired
	private RedisService redisService;// redis

	@Autowired
	private UploadFilesServer server;
	Logger logger = LoggerFactory.getLogger(InitContext.class);

	@SuppressWarnings("rawtypes")
	public WeContext init(HttpServletRequest req, HttpServletResponse resp)
			throws WeException, UnsupportedEncodingException, InterruptedException, ExecutionException {
		WeContext context = new WeContext();
		context.setRequest(req);
		context.setResp(resp);
		String uri = req.getServletPath().replace("/wecloud/", "");
		context.setTransactionId(uri);
		WeUser user = null;
		String contentType = req.getContentType();
		if(contentType.contains("multipart/form-data")){
			MultipartHttpServletRequest request = (MultipartHttpServletRequest) context.getRequest();
			logger.info("[请求处理开始]：["+context.getString("uri")+"],请求时间："+new Date());
			if (request.getParameter("JSESSIONID") != null && !"".equals(request.getParameter("JSESSIONID"))) {
				user = redisService.get((String) request.getParameter("JSESSIONID"));
				if (user == null) {
					throw new WeException(ErrorMsg.Error_0003);
				}
				context.setData("JSESSIONID", request.getParameter("JSESSIONID"));
				context.setUser(user);
			}
			if (user == null) {
				throw new WeException(ErrorMsg.Error_0003);
			}
			context.setData("uri", uri);
			// 处理文件信息
			context.setData("List", server.execute(context, request).get());
		} else if(contentType.contains("application/json") || contentType.contains("text/plain")) {
			String reqParam = getRequestContent(req);
			Map param = null;
			if(reqParam != null && !"".equals(reqParam)){
				param = JsonUtils.deserialize(reqParam, Map.class);
				context.setData(param);
				context.setData("reqParam", reqParam);
			}
			logger.info("[请求处理开始]：["+context.getString("uri")+"],请求参数："+context.getString("reqParam")+",请求时间："+new Date());
			if ("register".equals(uri)) {
				context.setData("uri", uri);
				return context;
			}
			String sessionid = param.get("JSESSIONID")== null ?"":(String)param.get("JSESSIONID");
			if (sessionid != null && !"".equals(sessionid)) {
				user = redisService.get(sessionid);
				if (user != null) {
					context.setUser(user);
				}
			}
		}
		return context;
	}

	/**
	 * 处理web请求的数据
	 * 
	 * @param request
	 * @return
	 */
	protected String getRequestContent(HttpServletRequest request) {
		InputStream is = null;
		String body = null;
		try {
			is = request.getInputStream();
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			byte[] data = new byte[8192];
			int rsize = 0;
			do {
				rsize = is.read(data);
				if (rsize > 0) {
					bout.write(data, 0, rsize);
				}
			} while (rsize > 0);
			body = new String(bout.toByteArray(), "utf-8");
			bout.close();
		} catch (Exception e) {
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
					logger.error("[处理字节流时异常]", e);
				}
			}
		}
		return body;
	}
}
